<template>
    <div class="ldm-page">
        <div class="page-bar">
            <a class="back" @click="goBack">
                <LeftOutlined /><span class="text">返回</span>
            </a>
            <span class="vsep">|</span>
            <span class="title">{{ isEdit ? '编辑' : '新增' }}</span>
        </div>

        <div class="content-area">
            <div class="body">
                <a-form :model="form" :label-col="{ style: 'width: 96px;' }"
                    :wrapper-col="{ style: 'max-width: 520px;' }">
                    <a-form-item label="查询关键词：" required>
                        <a-input v-model:value="form.query" placeholder="请输入查询关键词" />
                    </a-form-item>

                    <a-form-item label="标题：">
                        <a-input v-model:value="form.title" placeholder="可选" />
                    </a-form-item>

                    <a-form-item label="URL地址：" required>
                        <a-input v-model:value="form.page_url" placeholder="请输入链接 URL（如 https://...）" />
                    </a-form-item>

                    <a-form-item label="频道：">
                        <a-select v-model:value="form.sence" :options="categoryOptions" :loading="loadingCats"
                            allow-clear placeholder="请选择频道" style="width: 100%"
                            :getPopupContainer="(node: any) => node.parentNode" />
                    </a-form-item>

                    <a-form-item label="地理位置：">
                        <a-input v-model:value="form.position" placeholder="如 北京/上海/杭州…" />
                    </a-form-item>

                    <a-form-item label="摘要：">
                        <a-input v-model:value="form.summary" placeholder="可选" />
                    </a-form-item>

                    <a-form-item label="状态：">
                        <a-radio-group v-model:value="form.statusUi">
                            <a-radio value="enabled">启用</a-radio>
                            <a-radio value="disabled">停用</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>

            <div class="page-footer">
                <div class="footer-inner">
                    <a-button type="link" class="btn-cancel" @click="goBack">取消</a-button>
                    <span class="sep">|</span>
                    <a-button type="link" class="btn-ok" :loading="submitting" @click="onSubmit">确定</a-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { LeftOutlined } from '@ant-design/icons-vue'
import {
    getLinkInsertById,
    createLinkInsert,
    updateLinkInsert,
    getVerticalCategories,
    type LinkInsertItem,
    type VerticalCategory,
} from '@/api/modules/linkInsert.api'

const router = useRouter()
const route = useRoute()
const TAB_KEY = 'linkInsertion'

/* 路由状态 */
const isEdit = computed(() => String(route.query.mode || '') === 'edit')
const idRef = computed(() => (route.query.id ? String(route.query.id) : ''))

/** 表单 */
const form = reactive<{
    query: string | number | null
    title?: string | number | null
    page_url: string | number | null
    sence?: string | number | null
    position?: string | number | null
    summary?: string | number | null
    statusUi: 'enabled' | 'disabled'
}>({
    query: '',
    title: '',
    page_url: '',
    sence: '',
    position: '',
    summary: '',
    statusUi: 'enabled',
})

const submitting = ref(false)

/** —— 频道下拉 —— */
const categoryOptions = ref<{ label: string; value: string }[]>([])
const loadingCats = ref(false)
async function loadCategories() {
    loadingCats.value = true
    try {
        const cats = (await getVerticalCategories()) as VerticalCategory[]
        categoryOptions.value = (cats || []).map(c => ({ label: c.query, value: c.value }))
    } finally {
        loadingCats.value = false
    }
}

function safeTrim(v: unknown): string | undefined {
    if (v === undefined || v === null) return undefined
    const s = (typeof v === 'string') ? v : String(v)
    const t = s.trim()
    return t ? t : undefined
}

function toInput(v: unknown): string {
    if (v === undefined || v === null) return ''
    return typeof v === 'string' ? v : String(v)
}

/** 回填 */
function fillFormFromRow(r: Partial<LinkInsertItem> & Record<string, any>) {
    form.query = toInput(r.query ?? '')
    form.title = toInput(r.title ?? '')
    form.page_url = toInput(r.page_url ?? r.url ?? '')
    form.sence = toInput(r.sence ?? r.sence_code ?? r.channel ?? '')
    form.position = toInput(r.position ?? r.location ?? '')
    form.summary = toInput(r.summary ?? '')
    form.statusUi = r.status === 'published' ? 'enabled' : 'disabled'
}

/** 初始化 */
async function init() {
    await loadCategories()

    if (!isEdit.value) {
        fillFormFromRow({ query: '', title: '', page_url: '', sence: '', position: '', summary: '', status: 'published' })
        return
    }

    if (route.query.row) {
        try {
            const row = JSON.parse(decodeURIComponent(String(route.query.row)))
            fillFormFromRow(row)
            return
        } catch { /* ignore */ }
    }

    if (!idRef.value) return
    try {
        const data = await getLinkInsertById(idRef.value)
        fillFormFromRow(data)
    } catch (e: any) {
        message.error(e?.message || '加载失败')
    }
}

onMounted(init)
watch(() => ({ mode: route.query.mode, id: route.query.id, row: route.query.row }), () => init())

/** 返回 */
function backTarget() {
    const backTo = route.query.backTo
    const from = route.query.from as string | undefined
    if (backTo === 'tab' && from) return { path: from, query: { tab: TAB_KEY } }
    return { path: '/linkInsertion' }
}
function goBack() {
    router.replace(backTarget())
}

/** 提交 */
async function onSubmit() {
    const q = safeTrim(form.query)
    const pu = safeTrim(form.page_url)
    if (!q) return message.warning('请填写查询关键词')
    if (!pu) return message.warning('请填写 URL 地址')

    submitting.value = true
    try {
        const payload: Partial<LinkInsertItem> = {
            query: q,
            title: safeTrim(form.title),
            page_url: pu,
            sence: safeTrim(form.sence),    
            position: safeTrim(form.position),
            summary: safeTrim(form.summary),
            status: form.statusUi === 'enabled' ? 'published' : 'draft',
        }

        if (isEdit.value) {
            if (!idRef.value) throw new Error('缺少 ID，无法保存')
            await updateLinkInsert(idRef.value, payload)
        } else {
            await createLinkInsert(payload)
        }

        message.success('保存成功')
        goBack()
    } catch (e: any) {
        message.error(e?.message || '保存失败')
    } finally {
        submitting.value = false
    }
}
</script>

<style lang="less" scoped>
@pad-x: 24px;
@wrap-max: 520px;
@label-w: 96px;
@safe-bottom: env(safe-area-inset-bottom);

.ldm-page {
    background: #fff;
    border: 1px solid #eaeaea;
    border-radius: 6px;
    min-height: 100vh;
    min-height: 100dvh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.page-bar {
    display: flex;
    align-items: center;
    padding: 14px @pad-x;
}

.back {
    display: inline-flex;
    align-items: center;
    color: #81889c;
    font-size: 14px;
    cursor: pointer;
    text-decoration: none;
}

.back .anticon {
    margin-right: 6px;
}

.vsep {
    margin: 0 12px;
    color: #bfbfbf;
}

.title {
    font-size: 16px;
    font-weight: 600;
    color: #222;
}

.content-area {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: auto;
    padding-bottom: calc(16px + @safe-bottom);
}

.body {
    padding: 20px @pad-x 0 85px;
}

:deep(.ant-form-item) {
    margin-bottom: 20px;
}

:deep(.ant-form-item-label > label) {
    font-size: 14px;
}

.page-footer {
    position: static;
    margin-top: 16px;
    padding: 12px @pad-x calc(12px + @safe-bottom) @pad-x;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, .03);
}

.footer-inner {
    max-width: @wrap-max;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    flex-wrap: wrap;
    width: 100%;
    padding-left: @label-w;
}

.sep {
    color: #e5e7eb;
    line-height: 24px;
    height: 24px;
    display: inline-flex;
    align-items: center;
    margin: 0 2px;
}

.btn-cancel {
    height: 36px;
    padding: 0 16px;
    border-radius: 8px;
    background: #fafafa !important;
    border: 1px solid #e8e8e8 !important;
    color: #666 !important;
}

.btn-cancel:hover {
    background: #fff !important;
    color: #595959 !important;
    border-color: #d9d9d9 !important;
}

.btn-ok {
    height: 36px;
    padding: 0 20px;
    border-radius: 8px;
    font-weight: 600;
    background: #1677ff !important;
    border: 1px solid #1677ff !important;
    color: #fff !important;
}

.btn-ok:hover {
    filter: brightness(1.02);
    box-shadow: 0 2px 8px rgba(22, 119, 255, .2);
}
</style>
